﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.BomCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理添加流程命令
    /// </summary>
    public class ProcessInfoCreateCommandHandler : IRequestHandler<ProcessInfoCreateCommand, APIResult<object>>
    {
        
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 工艺流程仓储
        /// </summary>
        private readonly IBaseRepository<ProcessInfo> procRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="procRepository">工艺流程仓储</param>
        public ProcessInfoCreateCommandHandler(IMapper mapper,IBaseRepository<ProcessInfo> procRepository)
        {
            this.mapper = mapper;
            this.procRepository = procRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<object>> Handle(ProcessInfoCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var entity=mapper.Map<ProcessInfo>(request);
            entity.ProcessCode="GX"+DateTime.Now.ToString("yyyyMMddHHmmss");
           var i= await procRepository.AddAsync(entity);
            if (i > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = i;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
                result.data = i;
            }
            return await Task.FromResult(result);
        }
    }
}
